package system

import (
	"context"
	"regexp"
	"slices"
	"strconv"
	"strings"
	"time"

	"portal/internal/common"
	"portal/internal/errorx"
	"portal/internal/svc"
	"portal/internal/tool/auth"
	"portal/internal/types"
	"portal/model"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type EditDeptLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	menuModel model.SysMenuModel
	deptModel model.SysDeptModel
}

func NewEditDeptLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EditDeptLogic {
	return &EditDeptLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		menuModel: model.NewSysMenuModel(svcCtx.Orm),
		deptModel: model.NewSysDeptModel(svcCtx.Orm),
	}
}

func (l *EditDeptLogic) EditDept(req *types.EditDeptRequest) (resp *types.CommonResponse, err error) {
	// todo: add your logic here and delete this line
	err = auth.HasPermission(l.menuModel,l.ctx,"system:dept:edit")
	if err != nil {
		return nil,errorx.NewBizError(500,"权限不足")
	}
	
	authinfo,err := auth.GetAuth(l.ctx)
	if err != nil {
		return nil,err
	}

	roles,err := auth.GetRoles(l.ctx)
	if err != nil {
		return nil,err
	}
	strDeptId, err := auth.GetDeptId(l.ctx)
	if err != nil {
		return nil, errorx.TypeTransError
	}
	deptId, _ := strconv.Atoi(strDeptId)
	if isAdmin,_ := auth.IsAdmin(l.ctx); !isAdmin {
		// 判断是否拥有本部门的权限信息
		// err = l.deptModel.ExistByDIdRIds(l.ctx,nil,req.DeptId,roleIds)
		
		depts,err := getDepts(l.ctx,int64(deptId),roles,l.deptModel,&types.ListDeptRequest{})
		if err != nil {
			return nil,errorx.NewBizError(500,"部门信息查询失败")
		}
		isHas := slices.ContainsFunc(depts,func(n *types.Dept)bool{
			return n.DeptId == req.DeptId
		})
		if !isHas {
			return nil,errorx.Unauthorized
		}
	}

	dept,err := l.deptModel.FindOne(l.ctx,req.DeptId)
	if err != nil {
		return nil,errorx.SqlExistError
	}
	if len(req.ParentId) > 0 {
		parentId,err := strconv.Atoi(req.ParentId)
		if err != nil {
			return nil,errorx.ParamsError
		}
		if int64(parentId) != dept.ParentId{
			pDept,err := l.deptModel.FindOne(l.ctx,int64(parentId))
			if err != nil {
				return nil,err
			}
			//--------- 修改子部门的ancestors
			depts,err := l.deptModel.GetListBase(l.ctx,nil,dept.DeptId,false)
			if err != nil && err != sqlx.ErrNotFound {
				return nil,errorx.SqlSearchError
			}
			beforePrefixAnc := dept.Ancestors
			afterPrefixAnc := pDept.Ancestors + "," + strconv.Itoa(int(pDept.DeptId))
			for _,val := range depts {
				if val.DeptId != dept.DeptId {
					ancestors := val.Ancestors
					cuted,isCuted := strings.CutPrefix(ancestors,beforePrefixAnc)
					if !isCuted {
						return nil,errorx.NewBizError(500,"数据库数据异常")
					} 
					val.Ancestors = afterPrefixAnc + cuted
					err := l.deptModel.Edit(l.ctx,nil,val)
					if err != nil {
						return nil,err
					}
				}
			}
			dept.ParentId = int64(parentId)
			dept.Ancestors = pDept.Ancestors + "," + req.ParentId
		}
	}
	if len(req.DeptName) > 0 {
		dept.DeptName = req.DeptName
	}
	if req.OrderNum > 0 {
		dept.OrderNum = req.OrderNum
	}
	dept.OrderNum = req.OrderNum
	if len(req.Email) > 0 {
		reg := regexp.MustCompile(common.EmailFormat)
		if !reg.MatchString(req.Email) {
			return nil, errorx.NewBizError(500, "邮箱格式不正确")
		}
		dept.Email.String = req.Email
		dept.Email.Valid = true
	}
	if len(req.Phone) > 0 {
		reg := regexp.MustCompile(common.PhoneFormat)
		if !reg.MatchString(req.Phone) {
			return nil,errorx.NewBizError(500,"手机号码格式不正确")
		}
		dept.Phone.String = req.Phone
		dept.Phone.Valid = true
	}
	if len(req.Leader) > 0 {
		dept.Leader.String = req.Leader
	}
	if len(req.Status) > 0 {
		dept.Status = req.Status
	}
	if len(req.DelFlag) > 0 {
		dept.DelFlag = req.DelFlag
	}
	dept.UpdateBy = authinfo.UserName
	dept.UpdateTime = time.Now().Unix()
	err = l.deptModel.Edit(l.ctx,nil,dept)
	if err != nil {
		return nil,err
	}
	return &types.CommonResponse{
		Status: 200,
		Msg: "修改成功",
	},nil
}
